'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { role, nickNameLike, type } = query;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    raw: true,
    where,
  };
  options.include = [
    {
      model: ctx.model.WechatAccount,
    },
    {
      model: ctx.model.Phone,
    },
  ];
  switch (type) {
    // 被邀请者
    case 'invitees':
      console.log('ctx.state.user.role', ctx.state.user.role);
      switch (ctx.state.user.role) {
        case 'admin':
          if (query.inviterId) {
            where.inviterId = query.inviterId;
            options.attributes.push('nickname', 'pointBalance', 'fileHash', 'inviterId');
          } else {
            ctx.status = 403;
          }
          break;
        case 'facilitator':
          where.inviterId = ctx.state.user.sub;
          options.attributes.push('nickname', 'pointBalance', 'fileHash');
          console.log('invitees query.inviterId', query.inviterId);
          if (query.inviterId) {
            const inviter = await ctx.model.User.findById(query.inviterId);
            if (inviter.inviterId === ctx.state.user.sub) {
              where.inviterId = query.inviterId;
            }
          } else {
            options.attributes.push('phone', 'name');
          }
          break;
        case 'merchant':
          where.inviterId = ctx.state.user.sub;
          options.attributes.push('nickname', 'pointBalance', 'fileHash');
          console.log('invitees query.inviterId', query.inviterId);
          if (query.inviterId) {
            const inviter = await ctx.model.User.findById(query.inviterId);
            if (inviter.inviterId === ctx.state.user.sub) {
              where.inviterId = query.inviterId;
            }
          } else {
            options.attributes.push('phone', 'name');
          }
          break;
        case 'member':
          where.inviterId = ctx.state.user.sub;
          options.attributes.push('nickname', 'pointBalance', 'fileHash');
          console.log('invitees query.inviterId', query.inviterId);
          if (query.inviterId) {
            const inviter = await ctx.model.User.findById(query.inviterId);
            if (inviter.inviterId === ctx.state.user.sub) {
              where.inviterId = query.inviterId;
            }
          } else {
            options.attributes.push('phone', 'name');
          }
          break;
        default:
          ctx.status = 403;
      }
      break;
    default:

  }
  if (role) where.role = role;
  if (nickNameLike) where.nickname = { [ctx.model.Op.like]: `%${nickNameLike}%` };
  const {
    count: total, rows: list,
  } = await ctx.model.User.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  const { role } = ctx.state.user;
  if (role === 'admin') {
    ctx.validate({
      name: { type: 'string' },
      phone: { type: 'string' },
      role: { type: 'string' },
    });
    const { phone, role, name } = ctx.request.body;
    console.log('phonephonephonephone', phone);
    const phoneUser = await ctx.model.Phone.findByPk(phone);
    console.log('phoneUserphoneUserphoneUser', phoneUser);
    if (phoneUser) {
      console.log('if (phoneUser)if (phoneUser)phoneUser', phoneUser);
      const current = await ctx.model.User.findOne({ where: { id: phoneUser.userId } });
      console.log('if (phoneUser)if (phoneUser)current', current);
      const newUser = await current.update({ role, name });
      ctx.body = newUser;
    } else {
      console.log('else {else {else {');
      const user = await this.ctx.model.User.create({ role, name });
      console.log('await ctx.model.User.create user', user);
      const phoneUser = await this.ctx.model.Phone.create({ number: phone, userId: user.id });
      console.log('else {else {else { phoneUser', phoneUser);
      ctx.body = user;
    }
  } else {
    ctx.status = 403;
  }
};

exports.update = async ctx => {
  const user = await ctx.model.User.findByPk(ctx.params.id);
  if (user) {
    ctx.validate({
      phone: { type: 'string', required: false },
      role: { type: 'string', required: false },
      nickname: { type: 'string', required: false },
      name: { type: 'string', required: false },
    });
    const { imageHash } = ctx.request.body;
    if (imageHash) ctx.service.file.record('image', imageHash);
    ctx.body = await user.update(_.pickBy(
      _.pick(
        ctx.request.body,
        [ 'role', 'phone', 'nickname', 'name' ]
      ),
      value => value !== null
    ));
  } else {
    ctx.status = 404;
  }
};


exports.destroy = async ctx => {
  const user = await ctx.model.User.findByPk(ctx.params.id);
  if (user) {
    await user.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
